#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
处理三班制排班接口的参数
"""

import logging
from datetime import datetime, timedelta

# 配置日志
logger = logging.getLogger(__name__)

class ShiftParamsProcessor:
    """处理三班制排班接口的参数"""

    @staticmethod
    def process_shift_params(params, global_params):
        """处理三班制排班接口的参数

        Args:
            params: 接口传入的参数
            global_params: 全局配置参数

        Returns:
            处理后的参数字典
        """
        logger.info("开始处理三班制排班接口参数...")
        
        # 创建一个新的参数字典，避免修改原始参数
        processed_params = params.copy() if params else {}
        
        # 处理shift_mode参数（一天分几段）
        shift_mode = processed_params.get("shift_mode", global_params.get("shift_mode", 3))
        logger.info(f"处理shift_mode参数: {shift_mode}")
        
        # 验证shift_mode参数
        if not isinstance(shift_mode, int) or shift_mode not in [1, 2, 3]:
            logger.warning(f"无效的shift_mode参数: {shift_mode}，使用默认值: 3")
            shift_mode = 3
        
        # 更新shift_mode参数
        processed_params["shift_mode"] = shift_mode
        # 同时更新day_segments参数，确保一致性
        processed_params["day_segments"] = shift_mode
        
        # 处理custom_shifts参数（段数时间范围）
        custom_shifts = processed_params.get("custom_shifts", global_params.get("custom_shifts", []))
        logger.info(f"处理custom_shifts参数: {custom_shifts}")
        
        # 验证custom_shifts参数
        valid_custom_shifts = []
        if custom_shifts and isinstance(custom_shifts, list):
            # 检查是否是新格式的custom_shifts参数（包含start_time和end_time的对象数组）
            if len(custom_shifts) > 0 and isinstance(custom_shifts[0], dict):
                for i, shift in enumerate(custom_shifts):
                    if i >= shift_mode:
                        # 如果班次数量超过shift_mode，忽略多余的班次
                        logger.warning(f"忽略多余的班次: {shift}，因为shift_mode={shift_mode}")
                        break
                    
                    # 验证班次参数
                    if "start_time" in shift and "end_time" in shift:
                        # 验证时间格式
                        try:
                            start_time = datetime.strptime(shift["start_time"], "%H:%M").time()
                            end_time = datetime.strptime(shift["end_time"], "%H:%M").time()
                            
                            # 构建有效的班次参数
                            valid_shift = {
                                "name": shift.get("name", str(i+1)),  # 使用班次序号作为默认名称
                                "start_time": shift["start_time"],
                                "end_time": shift["end_time"],
                                "order": i+1  # 班次顺序
                            }
                            
                            valid_custom_shifts.append(valid_shift)
                            logger.info(f"有效的班次参数: {valid_shift}")
                        except ValueError:
                            logger.warning(f"无效的时间格式: {shift}")
                    else:
                        logger.warning(f"班次参数缺少start_time或end_time: {shift}")
        
        # 如果没有有效的自定义班次，根据shift_mode生成默认班次
        if not valid_custom_shifts:
            logger.info(f"没有有效的自定义班次，根据shift_mode={shift_mode}生成默认班次")
            
            if shift_mode == 1:
                # 一班制：全天24小时
                valid_custom_shifts = [{
                    "name": "1",
                    "start_time": "00:00",
                    "end_time": "24:00",
                    "order": 1
                }]
            elif shift_mode == 2:
                # 二班制：每班12小时
                valid_custom_shifts = [
                    {
                        "name": "1",
                        "start_time": "08:00",
                        "end_time": "20:00",
                        "order": 1
                    },
                    {
                        "name": "2",
                        "start_time": "20:00",
                        "end_time": "08:00",
                        "order": 2
                    }
                ]
            elif shift_mode == 3:
                # 三班制：每班8小时
                valid_custom_shifts = [
                    {
                        "name": "1",
                        "start_time": "06:00",
                        "end_time": "14:00",
                        "order": 1
                    },
                    {
                        "name": "2",
                        "start_time": "14:00",
                        "end_time": "22:00",
                        "order": 2
                    },
                    {
                        "name": "3",
                        "start_time": "22:00",
                        "end_time": "06:00",
                        "order": 3
                    }
                ]
        
        # 更新custom_shifts参数
        processed_params["custom_shifts"] = valid_custom_shifts
        
        # 处理time_interval_minutes参数（一个小时分段数）
        time_interval_minutes = processed_params.get("time_interval_minutes", global_params.get("time_interval_minutes", 20))
        logger.info(f"处理time_interval_minutes参数: {time_interval_minutes}")
        
        # 验证time_interval_minutes参数
        try:
            time_interval_minutes = int(time_interval_minutes)
            # 确保time_interval_minutes在10-60之间
            if time_interval_minutes < 10 or time_interval_minutes > 60:
                logger.warning(f"time_interval_minutes参数超出范围: {time_interval_minutes}，使用默认值: 20")
                time_interval_minutes = 20
            # 确保time_interval_minutes能被60整除
            elif 60 % time_interval_minutes != 0:
                # 找到最接近的能被60整除的值
                valid_intervals = [10, 12, 15, 20, 30, 60]
                closest = min(valid_intervals, key=lambda x: abs(x - time_interval_minutes))
                logger.warning(f"time_interval_minutes参数不能被60整除: {time_interval_minutes}，使用最接近的有效值: {closest}")
                time_interval_minutes = closest
        except (ValueError, TypeError):
            logger.warning(f"无效的time_interval_minutes参数: {time_interval_minutes}，使用默认值: 20")
            time_interval_minutes = 20
        
        # 更新time_interval_minutes参数
        processed_params["time_interval_minutes"] = time_interval_minutes
        
        # 计算time_slots_per_day参数
        time_slots_per_day = 24 * 60 // time_interval_minutes
        logger.info(f"计算time_slots_per_day参数: 24小时 * 60分钟 / {time_interval_minutes}分钟 = {time_slots_per_day}个时间段")
        processed_params["time_slots_per_day"] = time_slots_per_day
        
        # 确保generate_care_timeline参数为True
        processed_params["generate_care_timeline"] = True
        
        logger.info(f"处理后的参数: {processed_params}")
        return processed_params

    @staticmethod
    def validate_time_format(time_str):
        """验证时间格式是否为HH:MM"""
        try:
            datetime.strptime(time_str, "%H:%M")
            return True
        except ValueError:
            return False

    @staticmethod
    def generate_default_shifts(shift_mode):
        """根据班制模式生成默认班次"""
        if shift_mode == 1:
            # 一班制：全天24小时
            return [{
                "name": "1",
                "start_time": "00:00",
                "end_time": "24:00",
                "order": 1
            }]
        elif shift_mode == 2:
            # 二班制：每班12小时
            return [
                {
                    "name": "1",
                    "start_time": "08:00",
                    "end_time": "20:00",
                    "order": 1
                },
                {
                    "name": "2",
                    "start_time": "20:00",
                    "end_time": "08:00",
                    "order": 2
                }
            ]
        elif shift_mode == 3:
            # 三班制：每班8小时
            return [
                {
                    "name": "1",
                    "start_time": "06:00",
                    "end_time": "14:00",
                    "order": 1
                },
                {
                    "name": "2",
                    "start_time": "14:00",
                    "end_time": "22:00",
                    "order": 2
                },
                {
                    "name": "3",
                    "start_time": "22:00",
                    "end_time": "06:00",
                    "order": 3
                }
            ]
        else:
            # 默认三班制
            return ShiftParamsProcessor.generate_default_shifts(3)
